package com.lxf.cloudscheduled.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.lxf.cloudfeign.client.userClient.UserClient;
import com.lxf.cloudscheduled.bean.TaskBean;
import com.lxf.cloudscheduled.mapper.ScheduledTaskMapper;
import com.lxf.cloudscheduled.service.ScheduledTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 罗兴发
 * @data 2025/6/9 15:02
 * @description：任务-业务实现层
 */
@Service
@Slf4j
public class ScheduledTaskServiceImpl implements ScheduledTaskService {
    private static final String CRON_EXPRESSION = "0/5 * * * * ?"; // 每隔5秒执行一次
    @Resource
    ScheduledTaskMapper scheduledTaskMapper;
    @Resource
    private UserClient userClient;
    
    /**
     * 做定时检测
     */
    @Scheduled(cron = CRON_EXPRESSION)
    @Transactional(rollbackFor = Exception.class)//开启事务
    @Override
    @Async
    public void ScheduledTest(){
        try {
            log.info("已进入定时任务");
            List<TaskBean> task = scheduledTaskMapper.getAllTask();
            if (task.size()>0){
                log.info("任务不为空");
                for (TaskBean t:task) {
                    Integer status = t.getTStatus();
                    Integer isMsg = t.getIsMsg();
                    //只有状态为失败或成功，并且未发送消息通知的才可以发送消息通知
                    if (status!=0&&0==isMsg){
                        Integer userId = t.getUserId();
                        String content = t.getTContent();
                        //发送消息，请求体
                        JSONObject j = new JSONObject();
                        j.put("user_id",userId);
                        j.put("msg",content);
                        j.put("msg_type",2);
                        j.put("f_user_id",0);
                        userClient.sendPrivateMsg(j);
                        scheduledTaskMapper.updateTaskIsMsg(t.getTId(),1);
                    }
                }
            }
            int isMsg = 1;

            // 删除已发送消息通知的任务，避免数据库臃肿
            scheduledTaskMapper.deleteTaskByMsgStatus(isMsg);

            //将在线的用户ID设置为在线状态，其他的设置为离线状态
            userClient.setUserStatus();
        }catch (Exception e){
            log.info(e.getMessage());
            e.printStackTrace();
        }
    }
}
